<template>
  <el-card>
    <el-row :gutter="20" class="header">
      <el-col :span="7">
        <el-input
          :placeholder="$t('table.placeholder')"
          clearable
          v-model="queryForm.userName"
        ></el-input>
      </el-col>
      <el-button type="primary" :icon="Search" @click="initGetUsersList()">{{
        $t('table.search')
      }}</el-button>
      <el-button type="primary" @click="handleDialogValue()">{{
        $t('table.adduser')
      }}</el-button>
    </el-row>
    <el-table
      :data="tableData"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="index"
        :label="$t('table.index')"
        width="80"
      ></el-table-column>
      <el-table-column
        :width="item.width"
        :prop="item.prop"
        :label="$t(`table.${item.label}`)"
        v-for="(item, index) in options"
        :key="index"
      >
        <template v-slot="{ row }" v-if="item.prop === 'mg_state'">
          <el-switch
            v-model="row.mg_state"
            inline-prompt
            active-text="开"
            inactive-text="关"
            @change="changeState(row)"
          />
        </template>
        <template v-slot="{ row }" v-else-if="item.prop === 'create_time'">
          <!-- 处理日期格式化操作 -->
          {{ $filters.filterTimes(row.create_time) }}
        </template>
        <!-- #default 等价于 v-slot:default -->
        <template #default="{ row }" v-else-if="item.prop === 'action'">
          <el-button
            type="primary"
            size="small"
            :icon="Edit"
            @click="handleDialogValue(row)"
          ></el-button>
          <el-button type="warning" size="small" :icon="Setting"></el-button>
          <el-button
            type="danger"
            size="small"
            :icon="Delete"
            @click="delUser(row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:currentPage="queryForm.pagenum"
      v-model:page-size="queryForm.pagesize"
      :page-sizes="[5, 10, 15]"
      layout="prev, pager, next, jumper,->,sizes, total"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
  <!--
    这里的v-model可以传递也可以接收数据
    v-if="dialogVisible"解决上一次输入还存在
    这里的v-model 等价于 v-model 和 @update:modelValue="updateModelValue"
  -->
  <Dialog
    v-model="dialogVisible"
    :dialogTitle="dialogTitle"
    v-if="dialogVisible"
    @initUserList="initGetUsersList"
    :dialogTableValue="dialogTableValue"
  />
</template>

<script setup>
import { Edit, Setting, Delete, Search } from '@element-plus/icons-vue'
import { ref } from 'vue'
// options.js 定义了数据源信息
import { options } from './options'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from 'vue-i18n/dist/vue-i18n.esm-bundler'
import Dialog from './components/dialog.vue'
import { isNull } from '@/utils/filters.js'

// 定义对话框是否显示或隐藏变量 false不显示弹出框
const dialogVisible = ref(false)

const dialogTitle = ref('')

const dialogTableValue = ref({})

const i18n = useI18n()

const queryForm = ref({
  userName: '',
  pagenum: 1,
  pagesize: 10
})

const total = ref(0)

const tableData = ref([])

const initGetUsersList = async () => {
  const res = await getUser(queryForm.value)
  tableData.value = res.users
  total.value = res.total
  // console.log(res)
}
initGetUsersList()

const handleSizeChange = (pagesize) => {
  queryForm.value.pagesize = pagesize
  queryForm.value.pagenum = 1
  initGetUsersList()
}

const handleCurrentChange = (pagenum) => {
  queryForm.value.pagenum = pagenum
  initGetUsersList()
}

const changeState = async (info) => {
  await changeUserState(info.id, info.mg_state)
  ElMessage({
    type: 'success',
    message: i18n.t('message.updateSuccess')
  })
}

const handleDialogValue = (row) => {
  // 判断row是否为空，已经在utils/filters.js文件中暴露出了一个为空函数的判断
  if (isNull(row)) {
    dialogTitle.value = '添加用户'
    dialogTableValue.value = {}
  } else {
    dialogTitle.value = '编辑用户'
    dialogTableValue.value = JSON.parse(JSON.stringify(row)) // 深拷贝最后获取一个js对象
  }
  // 显示弹窗
  dialogVisible.value = true
}

// 删除用户
const delUser = (row) => {
  ElMessageBox.confirm(i18n.t('dialog.deleteTitle'), 'Warning', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    type: 'warning'
  })
    .then(async () => {
      await deleteUser(row.id)
      initGetUsersList()
      ElMessage({
        type: 'success',
        message: 'Delete completed'
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled'
      })
    })
}
</script>

<style lang="scss" scoped>
.header {
  padding-bottom: 16px;
  box-sizing: border-box;
}
:deep(.el-pagination) {
  padding-top: 16px;
  box-sizing: border-box;
  text-align: right;
}
</style>
